package com.jp.knowledge.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by jiayen on 16/11/4.
 */
public class JPRecycleViewHolder extends RecyclerView.ViewHolder {
    public JPRecycleViewHolder(View itemView) {
        super(itemView);
    }

    private final SparseArray<View> mViews = new SparseArray<>();


    public static JPViewHolder get(Context context, int LayoutID, ViewGroup parent, View convertView) {
        if (convertView == null)
            return new JPViewHolder(context, LayoutID, parent);
        return (JPViewHolder) convertView.getTag();
    }

    public View getItemView() {
        return itemView;
    }

    /**
     * @param viewId 控件ID
     * @param <T>    对象类型
     * @return 根据ID获取到的控件
     */
    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = itemView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T) view;
    }

    /**
     * 这里仅以TextView为例，其他的可以更具需求再做衍生
     *
     * @param viewId 控件ID
     * @param str    设置文本内容
     */
    public void setText(int viewId, String str) {
        ((TextView) getView(viewId)).setText(str);
    }
}
